 package com.webdesign.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.filechooser.FileSystemView;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.webdesign.dto.GradeInfoDTO;
import com.webdesign.entity.TbUser;

public class OuputExcelUtil {
	public static Boolean CreateExcel(String name, List<GradeInfoDTO> gradeinfos) {

		// 创建一个工作簿
		HSSFWorkbook workBook = new HSSFWorkbook();

		// 创建一个工作表，名为：name
		HSSFSheet sheet = workBook.createSheet(name);

		// 设置单元格的宽度(0:表示第一行的第一个单元格，1：第一行的第二个单元格...)
		sheet.setColumnWidth((short) 0, 2500);
		sheet.setColumnWidth((short) 1, 5000);
		sheet.setColumnWidth((short) 2, 5000);
		sheet.setColumnWidth((short) 3, 5000);
		sheet.setColumnWidth((short) 4, 5000);
		sheet.setColumnWidth((short) 5, 5000);

		// 创建一个单元格，从0开始
		HSSFRow row = sheet.createRow((short) 0);

		// 构造一个数组设置第一行之后的单元格
		HSSFCell cell[] = new HSSFCell[6];

		for (int i = 0; i < 6; i++) {
			cell[i] = row.createCell(i);
		}
		cell[0].setCellValue("学号");
		cell[1].setCellValue("姓名");
		cell[2].setCellValue("作业标题");
		cell[3].setCellValue("分数");
		cell[4].setCellValue("状态");
		cell[5].setCellValue("展示作业？");

		if (gradeinfos != null && gradeinfos.size() > 0) {
			// 循环list中的数据
			for (int i = 0; i < gradeinfos.size(); i++) {
				GradeInfoDTO gradeinfo = gradeinfos.get(i);
				HSSFRow dataRow = sheet.createRow(i + 1);
				HSSFCell data[] = new HSSFCell[6];

				for (int j = 0; j < 6; j++) {
					data[j] = dataRow.createCell(j);
				}
				data[0].setCellValue(gradeinfo.getUserid());
				data[1].setCellValue(gradeinfo.getUsername());
				data[2].setCellValue(gradeinfo.getTitle());
				data[3].setCellValue(gradeinfo.getScore());
				data[4].setCellValue(gradeinfo.getState());
				data[5].setCellValue(gradeinfo.getClassify());
			}

			try {
				// 输出成XLS文件
				FileSystemView fsv = FileSystemView.getFileSystemView();

				System.out.println(fsv.getHomeDirectory());
				File file = new File(fsv.getHomeDirectory()+"\\" + name + ".xls");
				FileOutputStream fos = new FileOutputStream(file);

				// 写入数据，并关闭文件
				workBook.write(fos);
				fos.close();
				return true;

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
	
	  
}
